#include "HealthComponent.h"
#include "GameObject.h"
#include "FlashComponent.h"

HealthComponent::HealthComponent(int p_minHealth, int p_maxHealth, float p_delayTime) : m_health(p_maxHealth), m_maxHealth(p_maxHealth), m_minHealth(p_minHealth)
	, m_targetTime(p_delayTime), m_elapsedTime(0.0f), m_canReceiveDamage(true), m_deathCallback(nullptr){}

HealthComponent::~HealthComponent(void){}

void HealthComponent::decreaseHealth(int p_value)
{
	if (m_canReceiveDamage)
	{
		if ((m_health - p_value) < m_minHealth)
			m_health = m_minHealth;
		else
			m_health -= p_value;
		m_canReceiveDamage = false;
	}

	if (m_health == m_minHealth)
	{
		m_canReceiveDamage = false;
		if (m_deathCallback != nullptr)
		{
			m_deathCallback();
			m_deathCallback = nullptr;
		}
	}
}

void HealthComponent::increaseHealth(int p_value)
{
	if ((m_health + p_value) > m_maxHealth)
		m_health = m_maxHealth;
	else
		m_health += p_value;
}

void HealthComponent::setHealth(int p_value)
{
	if (p_value > m_maxHealth)
		m_health = m_maxHealth;
	else if (p_value < m_minHealth)
		m_health = m_minHealth;
	else
		m_health = p_value;
}

void HealthComponent::init()
{

}

void HealthComponent::update(const GameTime& p_gameTime)
{
	if (!m_canReceiveDamage)
	{
		m_elapsedTime = std::min(m_elapsedTime + p_gameTime.deltaTime(), m_targetTime);
		if (m_elapsedTime >= m_targetTime)
		{
			m_elapsedTime = 0.0f;
			m_canReceiveDamage = true;
			IComponent* ic = getOwner()->getComponent("FlashComponent");
			if (ic != nullptr)
			{
				static_cast<FlashComponent*>(ic)->setActive(false);
			}
		}
	}
}